<?php

namespace app\api\service;

use app\api\model\BackListAreaModel;
use app\api\model\BackListCompanyModel;
use app\api\model\BackListKeywordsModel;
use app\api\model\ProductModel;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class BackListService extends Api
{
    protected static $instance;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
        {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 添加关键词黑名单
     */
    public function changeBackListKeywords($params)
    {
        $Validate = new Validate([
            'keywords' => 'require|array',
            'productIds' => 'require|array',
            'status' => 'require|number'
        ], [
            'keywords' => '关键词设置无效',
            'productIds' => '产品设置参数无效',
            'status' => '黑名单状态无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        Db::startTrans();
        try{
            $keyworsArr = BackListKeywordsModel::getInstance()->select([
                'keywords' => ['in', $params['keywords']],
                'product_id' => ['in', $params['productIds']]
            ]);
            if (!empty($keyworsArr))
            {
                BackListKeywordsModel::getInstance()->delete([
                    'id' => ['in', array_column($keyworsArr, 'id')]
                ]);
            }
            if (!empty($params['productId']))
            {
                BackListKeywordsModel::getInstance()->delete([
                    'product_id' => ['eq', $params['productId']]
                ]);
                $params['productIds'][] = $params['productId'];
                $params['productIds'] = array_unique($params['productIds']);
            }

            foreach ($params['productIds'] as $k => $v)
            {
                foreach ($params['keywords'] as $kk => $vv)
                {
                    $saveData[] = [
                        'keywords' => $vv,
                        'product_id' => $v,
                        'status' => $params['status'],
                        'c_time' => datetime(time(), 'Y-m-d H:i:s'),
                    ];
                }
            }
            $res = BackListKeywordsModel::getInstance()->insertAll($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取关键词黑名单列表接口
     */
    public function getBackListKeywords($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];

        if (!empty($params['productId']))
        {
            $where['product_id'] = ['eq', $params['productId']];
        }
        if (!empty($params['keywords']))
        {
            $where['keywords'] = ['like', $params['keywords']];
        }

        $whereArr = BackListKeywordsModel::getInstance()->select($where, '*', $start, $limit, 'c_time ASC', 'product_id');

        $list = BackListKeywordsModel::getInstance()->select([
            'product_id' => ['in', array_column($whereArr, 'product_id')]
        ], 'id,keywords,product_id,status,c_time', 0, 100000, 'c_time ASC');
        $proNames = ProductModel::getInstance()->column([], 'product_name');

        $result = [];
        foreach ($list as $k => $v)
        {
            $result[$v['product_id']]['productId'] = $v['product_id'];
            $result[$v['product_id']]['productName'] = isset($proNames[$v['product_id']]) ? $proNames[$v['product_id']] : '';
            $result[$v['product_id']]['keywords'][] = $v['keywords'];
            $result[$v['product_id']]['status'] = $v['status'];
            $result[$v['product_id']]['c_time'] = $v['c_time'];
        }

        return [
            'total' => BackListKeywordsModel::getInstance()->count($where),
            'list' => array_values($result)
        ];
    }

    /**
     * 获取产品黑名单关键词详情
     */
    public function getBackListKeywordsInfo($params)
    {
        $Validate = new Validate([
            'productId' => 'require',
        ], [
            'productId' => '产品标识无效',
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $list = BackListKeywordsModel::getInstance()->select([
            'product_id' => ['eq', $params['productId']]
        ]);
        return [
            'productId' => $params['productId'],
            'productName' => ProductModel::getInstance()->productValue([
                'id' => ['eq', $params['productId']]
            ], 'product_name'),
            'keywords' => array_column($list, 'keywords'),
            'status' => isset($list[0]['status']) ? $list[0]['status'] : 1
        ];
    }

    /**
     * 设置 公司黑名单
     */
    public function changeCompanyBackList($params)
    {
        $Validate = new Validate([
            'companyName' => 'require',
            'companyCode' => 'require',
            'productIds' => 'require|array',
            'status' => 'require'
        ], [
            'companyName' => '黑名单公司名称无效',
            'companyCode' => '黑名单公司编码无效',
            'productIds' => '黑名单产品设置无效',
            'status' => '公司黑名单状态无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        Db::startTrans();
        try{
            if (!empty($params['bcId']))
            {
                if (BackListCompanyModel::getInstance()->find([
                    'code' => ['eq', str_replace(' ', '', $params['companyCode'])],
                    'id' => ['neq', $params['bcId']]
                ]))
                {
                    $this->error('已存在该公司黑名单，请不要重复设置');
                }
                $saveData = [
                    'name' => $params['companyName'],
                    'code' => str_replace(' ', '', $params['companyCode']),
                    'product_id' => implode(',', $params['productIds']),
                    'status' => implode(',', $params['status']),
                    'u_time' => datetime(time(), 'Y-m-d H:i:s'),
                ];
                $res = BackListCompanyModel::getInstance()->update([
                    'id' => ['eq', $params['bcId']]
                ], $saveData);
            }else{
                if (BackListCompanyModel::getInstance()->find([
                    'code' => ['eq', str_replace(' ', '', $params['companyCode'])]
                ]))
                {
                    $this->error('已存在该公司黑名单，请不要重复添加');
                }
                $saveData = [
                    'name' => $params['companyName'],
                    'code' => str_replace(' ', '', $params['companyCode']),
                    'product_id' => implode(',', $params['productIds']),
                    'status' => implode(',', $params['status']),
                    'c_time' => datetime(time(), 'Y-m-d H:i:s'),
                ];
                $res = BackListCompanyModel::getInstance()->insert($saveData);
            }
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->success($e->getMessage());
        }
    }

    /**
     * 获取公司黑名单列表
     */
    public function getCompanyBackList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];

        if (!empty($params['companyName']))
        {
            $where['name'] = ['like', '%'.$params['companyName'].'%'];
        }
        if (!empty($params['companyCode']))
        {
            $where['code'] = ['like', '%'.$params['companyCode'].'%'];
        }
        if (!empty($params['productId']))
        {
            $where['product_id'] = ['like', '%'.$params['productId'].'%'];
        }
        $proNames = ProductModel::getInstance()->column([], 'product_name');

        $list = BackListCompanyModel::getInstance()->select($where, '*', $start, $limit);
        foreach ($list as $k => &$v)
        {
            foreach (explode(',', $v['product_id']) as $kk => $vv)
            {
                $v['productName'][] = isset($proNames[$vv]) ? $proNames[$vv] : '';
            }
        }
        return [
            'total' => BackListCompanyModel::getInstance()->count($where),
            'list' => $list
        ];
    }

    /**
     * 获取公司黑名单详情
     */
    public function getCompanyBackListInfo($params)
    {
        $Validate = new Validate([
            'bcId' => 'require',
        ], [
            'bcId' => '公司黑名单标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $info = BackListCompanyModel::getInstance()->find([
            'id' => ['eq', $params['bcId']]
        ]);
        $proNames = ProductModel::getInstance()->column([], 'product_name');
        $info['product_id'] = explode(',', $info['product_id']);
        foreach ($info['product_id'] as $k => $v)
        {
            if (isset($proNames[$v]))
            {
                $info['productName'][] = $proNames[$v];
            }
        }
        $info['status'] = explode(',', $info['status']);
        return $info;
    }

    /**
     * 设置拒保地区
     */
    public function changeAreaBackList($params)
    {
        $Validate = new Validate([
            'province' => 'require|array',
            'productIds' => 'require|array',
            'status' => 'require',
        ], [
            'province' => '拒保地区设置无效',
            'productIds' => '拒保方案设置无效',
            'status' => '拒保状态设置无效'
        ]);
        $Validate2 = new Validate([
            'city' => 'require|array',
            'productIds' => 'require|array',
            'status' => 'require',
        ], [
            'city' => '拒保地区设置无效',
            'productIds' => '拒保方案设置无效',
            'status' => '拒保状态设置无效'
        ]);
        $Validate3 = new Validate([
            'area' => 'require|array',
            'productIds' => 'require|array',
            'status' => 'require',
        ], [
            'area' => '拒保地区设置无效',
            'productIds' => '拒保方案设置无效',
            'status' => '拒保状态设置无效'
        ]);
        if (!$Validate->check($params) && !$Validate2->check($params) && !$Validate3->check($params))
        {
            $this->error('拒保信息设置无效');
        }
        Db::startTrans();
        try{
            if (!empty($params['productId']))
            {
                BackListAreaModel::getInstance()->delete([
                    'product_id' => ['eq', $params['productId']]
                ]);
                $params['productIds'][] = $params['productId'];
            }
            foreach ($params['productIds'] as $k => $v)
            {
                $saveData[] = [
                    'province' => isset($params['province']) ? implode(',', $params['province']) : '',
                    'city' => isset($params['city']) ? implode(',', $params['city']) : '',
                    'area' => isset($params['area']) ? implode(',', $params['area']) : '',
                    'product_id' => $v,
                    'status' => $params['status'],
                    'c_time' => datetime(time(), 'Y-m-d H:i:s'),
                ];
            }
            $res = BackListAreaModel::getInstance()->insertAll($saveData);
            Db::commit();
            return $res;
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取拒保地区列表
     */
    public function getAreaBackList($params)
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 15);
        $start = ($page - 1) * $limit;

        $where = [];
        if (!empty($params['productId']))
        {
            $where['product_id'] = ['eq', $params['productId']];
        }
        $whereArr = BackListAreaModel::getInstance()->select($where, '*', $start, $limit, 'c_time', 'product_id');
        $list = BackListAreaModel::getInstance()->select([
            'product_id' => ['in', array_column($whereArr, 'product_id')]
        ], '*', 0, 100000, 'c_time');
        $result = $arr = [];
        foreach ($list as $k => $v)
        {
            $arr[$v['product_id']]['province'][] = $v['province'];
            $arr[$v['product_id']]['city'][] = $v['city'];
            $arr[$v['product_id']]['area'][] = $v['area'];
            $arr[$v['product_id']]['product_id'] = $v['product_id'];
            $arr[$v['product_id']]['status'] = $v['status'];
        }
        $proNames = ProductModel::getInstance()->column([], 'product_name');
        foreach (array_values($arr) as $k => $v)
        {
            $result[$k]['province'] = !empty($v['province']) ? array_values(Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $v['province']))]
            ])->column('name', 'id')) : '';
            $result[$k]['city'] = !empty($v['city']) ? array_values(Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $v['city']))]
            ])->column('name', 'id')) : '';
            $result[$k]['area'] = !empty($v['area']) ? array_values(Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $v['area']))]
            ])->column('name', 'id')) : '';
            $result[$k]['productId'] = $v['product_id'];
            $result[$k]['productName'] = isset($proNames[$v['product_id']]) ? $proNames[$v['product_id']] : '';
            $result[$k]['status'] = $v['status'];
        }
        return [
            'total' => BackListAreaModel::getInstance()->count($where),
            'list' => $result,
        ];
    }

    /**
     * 获取拒保地区详情
     */
    public function getAreaBackListInfo($params)
    {
        $Validate = new Validate([
            'productId' => 'require|number'
        ], [
            'productId' => '产品标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $list = BackListAreaModel::getInstance()->select([
            'product_id' => ['eq', $params['productId']]
        ]);
        $proName = ProductModel::getInstance()->productValue([
            'id' => ['eq', $params['productId']]
        ], 'product_name');
        $provinceIds = array_column($list, 'province');
        $cityIds = array_column($list, 'city');
        $areaIds = array_column($list, 'area');
        return [
            'productId' => $params['productId'],
            'productName' => $proName,
            'province' => Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $provinceIds))]
            ])->column('id,name'),
            'city' => Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $cityIds))]
            ])->column('id,name'),
            'area' => Db::name('t_area')->where([
                'id' => ['in', explode(',', implode(',', $areaIds))]
            ])->column('id,name'),
            'status' => isset($list[0]['status']) ? $list[0]['status'] : 1
        ];
    }

    /**
     * 删除指定产品拒保地区
     */
    public function unsetProductArea($params)
    {
        $Validate = new Validate([
            'productId' => 'require',
        ], [
            'productId' => '产品标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $res = BackListAreaModel::getInstance()->delete([
            'product_id' => ['eq', $params['productId']]
        ]);
        return $res;
    }

    /**
     * 删除公司黑名单
     */
    public function unsetCompany($params)
    {
        $Validate = new Validate([
            'id' => 'require',
        ], [
            'id' => '删除标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $res = BackListCompanyModel::getInstance()->delete([
            'id' => ['eq', $params['id']]
        ]);
        return $res;
    }

    /**
     * 删除指定产品拒保关键词
     */
    public function unsetProductKeywords($params)
    {
        $Validate = new Validate([
            'productId' => 'require',
        ], [
            'productId' => '产品标识无效'
        ]);
        if (!$Validate->check($params))
        {
            $this->error($Validate->getError());
        }
        $res = BackListKeywordsModel::getInstance()->delete([
            'product_id' => ['eq', $params['productId']]
        ]);
        return $res;
    }
}